<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html{
            width: 100%;
            height: 100%;
            margin:0;
            font-family:"微软雅黑";
        }
        #allmap{
            height:720px;
            width:100%;
            height: 95%
        }
        #r-result{
            width:100%;
            font-size:10px;
            text-align: center;
            margin-top:7px;
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ygKlbdI2D58F43aRkPvrQ5TCnV1HIui2"></script>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <title>城市名定位</title>
</head>
<body>
<div id="allmap"></div>
<div id="r-result">
    <button id="querynow">实时查看 </button>
    <button id="queryhistory">实时轨迹 </button>
    <button id="historyorbit">历史轨迹</button>
    <input id="input" type="text" value="请输入告警标签id">
    <button id="submit">发送告警</button>
    <button id="display">显示标签</button>
    <button id="hide">隐藏标签</button>



</div>
<div id="output"></div>
</body>
</html>
<script type="text/javascript">
    // 百度地图API功能cd
    var map = new BMap.Map("allmap");
    map.centerAndZoom(new BMap.Point(116.331398,39.897445),11);
    map.enableScrollWheelZoom(true);

    window.addEventListener("load", function(evt) {
        var markerDisplay = true; //是否显示实时标签
        var querystring;
        var output = document.getElementById("output");
        var ws;
        var print = function(message) {
            var d = document.createElement("div");
            d.innerHTML = message;
            output.appendChild(d);
        };

        //open 是发送了http调用，然后服务端通过upgrader对象握手
        document.getElementById("querynow").onclick = function(evt) {
            console.log("建立链接，开始接收数据")
            if (ws) {
                return false;
            }

            ws = new WebSocket('ws://' + window.location.host + '/udp');

            ws.onopen = function(evt) {
                //print("OPEN");
            }
            ws.onclose = function(evt) {
                //print("CLOSE");
                ws = null;
            }
            ws.onmessage = function(evt) {

                var myIcon = new BMap.Icon("http://rundeep.f3322.org:19000/static/img/person_11.9.png", new BMap.Size(32, 70), {    //小车图片

                    //offset: new BMap.Size(0, -5),    //相当于CSS精灵
                    imageOffset: new BMap.Size(0, 0)    //图片的偏移量。为了是图片底部中心对准坐标点。
                });
                console.log("message: ", evt.data)

                if (evt.data.substring(0, 5) == "alarm") {
                    console.log("出现告警")
                    alert(evt.data.substring(5,8)+"号标签发生告警")
                } else{

                    console.log(evt.data.split("and"))
                var longitude = evt.data.split("and")[0]
                var latitude = evt.data.split("and")[1]
                var new_point = new BMap.Point(longitude, latitude);
                //var marker = new BMap.Marker(new_point);  // 创建标注
                console.log("new_point:", new_point)


                //坐标转换完之后的回调函数
                translateCallback = function (data) {
                    if (data.status === 0) {
                        var marker = new BMap.Marker(data.points[0], {icon: myIcon});
                        console.log("makerpoint: ", marker.point)
                        if(markerDisplay == true){
                            map.addOverlay(marker);
                        }


                        setTimeout(function () {
                            map.clearOverlays();//清除所有坐标点
                        }, 2000)

                        var label = new BMap.Label("员工", {offset: new BMap.Size(20, -10)});
                        marker.setLabel(label); //添加百度label
                        // bm.setCenter(data.points[0]);
                    }
                }

                var convertor = new BMap.Convertor();//创建一个坐标转换的实例
                var pointArr = [];
                pointArr.push(new_point);
                convertor.translate(pointArr, 1, 5, translateCallback)

                //map.panTo(new_point);
            }

            }

            ws.onerror = function(evt) {
                //print("ERROR: " + evt.data);
            }
            return false;
        };
　　　　　


        //实时轨迹
        document.getElementById("queryhistory").onclick = function(evt){
            console.log("querynow")
            if (ws) {
                return false;
            }
            ws = new WebSocket('ws://' + window.location.host + '/udp');

            ws.onopen = function(evt) {
                //print("OPEN");
            }
            ws.onclose = function(evt) {
                //print("CLOSE");
                ws = null;
            }
            var pois = [];

            ws.onmessage = function(evt) {


                // var myIcon = new BMap.Icon("http://rundeep.f3322.org:19000/static/img/person_11.9.png", new BMap.Size(32, 70), {    //小车图片
                //
                //     //offset: new BMap.Size(0, -5),    //相当于CSS精灵
                //     imageOffset: new BMap.Size(0, 0)    //图片的偏移量。为了是图片底部中心对准坐标点。
                // });
                console.log("message: ", evt.data)

                    console.log(evt.data.split("and"))
                    var longitude = evt.data.split("and")[0]
                    var latitude = evt.data.split("and")[1]
                    var new_point = new BMap.Point(longitude, latitude);
                    //var marker = new BMap.Marker(new_point);  // 创建标注
                    console.log("new_point:", new_point)


                    //标转换完之后的回调函数
                    translateCallback = function (data) {
                        var myP = new BMap.Point(data.points[0]["lng"], data.points[0]["lat"]);


                        // console.log("myP9:",myP9)
                        // console.log("myP10:",myP10)

                        console.log("start..")

                        var sy = new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
                            scale: 0.6,//图标缩放大小
                            strokeColor:"transparent",//设置矢量图标的线填充颜色
                            strokeWeight: '2',//设置线宽
                        });
                        var icons = new BMap.IconSequence(sy, '10', '30');
                        pois.push(myP);
                        console.log("points:",pois)
                        // 创建polyline对象
                        var polyline =new BMap.Polyline(pois, {
                            enableEditing: false,//是否启用线编辑，默认为false
                            enableClicking: true,//是否响应点击事件，默认为true
                            icons:[icons],
                            strokeWeight:'4',//折线的宽度，以像素为单位
                            strokeOpacity: 0.8,//折线的透明度，取值范围0 - 1
                            strokeColor:"#0000cd" //折线颜色
                        });

                        map.addOverlay(polyline);          //增加折线
                    }


                    var convertor = new BMap.Convertor();//创建一个坐标转换的实例
                    var pointArr = [];
                    pointArr.push(new_point);
                    convertor.translate(pointArr, 1, 5, translateCallback)
                    //map.panTo(new_point);
                }


            ws.onerror = function(evt) {
                //print("ERROR: " + evt.data);
            }


            return false;
        };


        //查询历史轨迹
        document.getElementById("historyorbit").onclick = function(){

            var labelname = prompt("请输入您要查询的标签id","001"); //将输入的内容赋给变量 name ，
            //这里需要注意的是，prompt有两个参数，前面是提示的话，后面是当对话框出来后，在对话框里的默认值
            if (labelname)//如果返回的有内容
            {
                var starttime = prompt("请输入起始时间", "2019-02-24 10:30:10");
                var endtime = prompt("请输入结束时间", "2019-02-24 10:40:10");
                var duratime = starttime + "to" + endtime;
            }

            var querydata = {labelname:labelname,duratime:duratime};
            querystring = JSON.stringify(querydata);

            $.ajax({
                type:"POST",
                url:"/querybyid",
                data:{subject:querystring},
                // dataType: "json",
                // contentType: "application/json; charset=utf-8",

                success:function(result){

                    //获取json元素个数
                    　　var count = Object.keys(result).length;
                       console.log(result[0].data)
　
                 //  　　  var myP1 = ''  //起点
                 // 　　　  var myP2 = '';    //终点
                        var longitude= result[0].split("and")[0];
                        var latitude = result[0].split("and")[1];
                        var start_point = new BMap.Point(longitude,latitude);
                        var end_point = new BMap.Point(result[count-1].split("and")[0],result[count-1].split("and")[1]);

                        console.log("start_point:",start_point);
                        console.log("end_point:",end_point);

                        translateCallback = function (data) {
                            if (data.status === 0) {

                                    var myP1 = new BMap.Point(data.points[0]["lng"], data.points[0]["lat"]);
                                    var myP2 = new BMap.Point(data.points[1]["lng"],data.points[1]["lat"]);
                                    var myP3 = new BMap.Point(data.points[2]["lng"],data.points[2]["lat"]);
                                    var myP4 = new BMap.Point(data.points[3]["lng"],data.points[3]["lat"]);
                                    var myP5 = new BMap.Point(data.points[4]["lng"],data.points[4]["lat"]);
                                    var myP6 = new BMap.Point(data.points[5]["lng"],data.points[5]["lat"]);
                                    var myP7 = new BMap.Point(data.points[6]["lng"],data.points[6]["lat"]);
                                    var myP8 = new BMap.Point(data.points[7]["lng"],data.points[7]["lat"]);
                                    var myP9 = new BMap.Point(data.points[8]["lng"],data.points[8]["lat"]);
                                    var myP10 = new BMap.Point(data.points[9]["lng"],data.points[9]["lat"]);

                                    console.log("myP1:",myP1)
                                    console.log("myP10:",myP10)

                                    console.log("start..")

                                var sy = new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
                                    scale: 0.6,//图标缩放大小
                                    strokeColor:'#fff',//设置矢量图标的线填充颜色
                                    strokeWeight: '2',//设置线宽
                                });
                                var icons = new BMap.IconSequence(sy, '10', '30');
                                // 创建polyline对象
                                var pois = [myP1,myP2,myP3,myP4,myP5,myP6,myP7,myP8,myP9,myP10];
                                var polyline =new BMap.Polyline(pois, {
                                    enableEditing: false,//是否启用线编辑，默认为false
                                    enableClicking: true,//是否响应点击事件，默认为true
                                    icons:[icons],
                                    strokeWeight:'8',//折线的宽度，以像素为单位
                                    strokeOpacity: 0.8,//折线的透明度，取值范围0 - 1
                                    strokeColor:"#18a45b" //折线颜色
                                });

                                map.addOverlay(polyline);          //增加折线

                                 }
                            }

                        var convertor = new BMap.Convertor();
                        // console.log("points: ", points[j])
                        var pointArr = [];
                        console.log("pointArr: ", pointArr)

                    　　 var num = parseInt((count-1)/9)
                        console.log("num: ",num)
                        for(var i = 0; i < count-1; i = i+ num){
                            pointArr.push(new BMap.Point(result[i].split("and")[0],result[i].split("and")[1]))
                        }
                       // pointArr.push(start_point);
                        pointArr.push(end_point);
                        console.log("pointArr: ",pointArr)
                        convertor.translate(pointArr, 1, 5, translateCallback);

                },
                error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    alert(textStatus);
                }
            });

        };
        //给标签发送告警信息
        document.getElementById("submit").onclick = function(evt) {
            if (!ws) {
                return false;
            }
            //print("SEND: " + input.value);
            ws.send(input.value);
            return false;
        };

        //显示标签
        document.getElementById("display").onclick = function(evt) {
            console.log("显示标签信息");
            markerDisplay = true;
        };


        //隐藏标签
        document.getElementById("hide").onclick = function(evt) {
            console.log("隐藏标签信息");
            markerDisplay = false;

            //关闭websocket链接
            // if (!ws) {
            //     return false;
            // }
            //ws.close();
            //return false;
        };

    });

</script>
